package com.dnapipeline.modelManage.service;

import com.dnapipeline.modelManage.entity.DeviceModel;
import com.dnapipeline.modelManage.entity.ProfileModel;
import com.dnapipeline.modelManage.repository.DeviceRepository;
import com.dnapipeline.modelManage.repository.ProfileRepository;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;
import java.util.ArrayList;

@Service
public class DeviceService {

    @Autowired
    private DeviceRepository deviceRepository;

    @Autowired
    private ProfileRepository profileRepository;

    public List<DeviceModel> findAll() {
        return deviceRepository.findAll();
    }

    public DeviceModel create(DeviceModel device) {
        String profileJson = device.getProfileJson();
        // 解析profileJson，创建对应的ProfileModel列表
        List<ProfileModel> profiles = parseProfileJson(profileJson, device);
        if(profiles != null) {
            // 通过profileRepository.save(profile)保存ProfileModel
            for (ProfileModel profile : profiles) {
                profileRepository.save(profile);
            }
        }

        // deviceKey在DeviceModel的无参构造方法中自动生成
        return deviceRepository.save(device);
    }

    public Optional<DeviceModel> findById(String deviceKey) {
        return deviceRepository.findById(deviceKey);
    }

    public DeviceModel update(String deviceKey, DeviceModel deviceDetails) {
        Optional<DeviceModel> optionalDevice = deviceRepository.findById(deviceKey);
        if(optionalDevice.isPresent()){
            DeviceModel device = optionalDevice.get();
            device.setDeviceName(deviceDetails.getDeviceName());
            device.setDeviceNetwork(deviceDetails.getDeviceNetwork());
            device.setProfileJson(deviceDetails.getProfileJson());
            return deviceRepository.save(device);
        }
        return null;
    }

    @Transactional
    public void delete(String deviceKey) {
        // 首先删除与deviceKey相等的所有ProfileModel
        profileRepository.deleteByDeviceKey(deviceKey);
        
        // 然后删除Device
        deviceRepository.deleteById(deviceKey);
    }

    // 通过deviceKey获取对应的ProfileModel列表

    public List<ProfileModel> parseProfileJson(String profileJson, DeviceModel device){
        // 如果profileJson的格式不是json，返回空列表
        if (!profileJson.startsWith("{")) {
            return null;
        }

        List<ProfileModel> profiles = new ArrayList<>();
        ObjectMapper objectMapper = new ObjectMapper();

        try {
            JsonNode rootNode = objectMapper.readTree(profileJson);
            String deviceKey = device.getDeviceKey(); // 假设deviceKey已生成

            // 如果deviceInfo节点不为空，将deviceInfo节点下的信息变为rootNode
            if (rootNode.has("deviceInfo")) {
                rootNode = rootNode.get("deviceInfo");
            }

            String deviceName = device.getDeviceName();

            // 遍历services数组
            for (JsonNode serviceNode : rootNode.get("services")) {
                String serviceId = serviceNode.get("serviceId").asText();
                String serviceNameEn = serviceNode.get("serviceName").asText();

                // 遍历characteristics
                for (JsonNode charNode : serviceNode.get("characteristics")) {
                    ProfileModel profile = new ProfileModel();
                    profile.setDeviceKey(deviceKey);

                    // 生成复合主键（示例：serviceId+characteristicName+随机数）
                    profile.setProfileModelKey(deviceName + '_' + serviceId + "_" + charNode.get("characteristicName").asText());

                    // 映射基础字段
                    profile.setServiceNameEn(serviceNameEn);
                    profile.setCharacteristicName(charNode.get("characteristicName").asText());
                    profile.setPermissions(charNode.get("method").asText());
                    profile.setCharacteristicType(charNode.get("characteristicType").asText());

                    // 映射characteristicNodeId字段，判空
                    if (charNode.has("NodeId")) {
                        profile.setCharacteristicNodeId(charNode.get("NodeId").asText());
                    }

                    // 处理枚举类型（descCh取第一个枚举项的descCh）
                    if ("enum".equals(profile.getCharacteristicType())) {
                        JsonNode enumList = charNode.get("enumList");
                        if (!enumList.isEmpty()) {
                            profile.setDescCh(enumList.get(0).get("descCh").asText());
                        }
                        // 将枚举列表存储到value字段
                        profile.setValue(objectMapper.writeValueAsString(enumList));
                    } else {
                        // 非枚举类型处理（如string/uint8等）
                        profile.setValue(charNode.has("value") ? charNode.get("value").asText() : "");
                    }

                    profiles.add(profile);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("解析profileJson失败: " + e.getMessage());
        }

        return profiles;
    }

}
